package com.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//监听器 web服务器开始运行时会运行
public class ContextLoaderListener implements ServletContextListener {
    //初始化方法
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //ServletContext域对象
        ServletContext servletContext = servletContextEvent.getServletContext();


        //创建容器 缺点:配置文件名写死了 优化:写在web.xml里面设置为全局初始参数
        //ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过域对象读取web.xml全局参数
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        //通过读取到的参数来生成容器
        ApplicationContext app=new ClassPathXmlApplicationContext(contextConfigLocation);

        //把容器放入域中 写一个工具类WebApplicationContextUtils获得容器
        servletContext.setAttribute("app",app);
        System.out.println("spring容器创建完毕");

    }
    //销毁方法
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
